import {createSlice} from '@reduxjs/toolkit'
import axios from 'axios'

const foodSlice = createSlice({
    name: 'food',
    initialState: {
        foodsList: [],
        activeIndex: 0,
        cartList: []
    },
    // actionCreator
    reducers: {
        // 设置food列表数据
        setFoodList(state,action) {
            state.foodsList = action.payload
        },
        // 设置分类当前活动index
        setActiveIndex(state,action) {
            state.activeIndex = action.payload
        },
        // 清空购物车
        clearCart(state){
            console.log("clearCart")
            state.cartList = []
        },
        // 添加购物车
        addCart(state,action) {
            const item = state.cartList.find(d => d.id === action.payload.id)
            if(item) {
                item.count++;
            }else {
                state.cartList.push(action.payload)
            }
            
        },
        // 加
        onPlus(state,action) {
            const item = state.cartList.find(d => d.id === action.payload.id)
            item.count++;
        },
        // 减
        onMinus(state,action) {
            const item = state.cartList.find(d => d.id === action.payload.id)
            if(item.count > 0) {
                item.count--;
            }
        }
    }
})

const { setFoodList,setActiveIndex,onPlus,onMinus,addCart,clearCart } = foodSlice.actions
// 异步
const fetchFoodList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        dispatch(setFoodList(res.data))
    }
}


export { fetchFoodList,setActiveIndex,onPlus,onMinus,addCart,clearCart }
export default foodSlice.reducer